<?php
/*
公共action调用库;
*/
class GlobalAction extends Action{
	var $cookie_status = 1;
	function _initialize(){	
		// ob_start();		
		//L(LC('@.Conf.Lang',true));/*加载语言包; */	
		LC("@.Conf.Defined");
		//加载自定义函数库{常规函数库};
		LC("@.Help.Common");		 
		//加载公共常用操作;
		LC("@.Lib.Mylib");
		LC("@.Lib.Mdlerror");
		$GLOBALS["err"]= new Mdlerror('message');
		$GLOBALS["_CFG"]=Mylib::shopconfig();
		G('err',$GLOBALS["err"]) ;
		G('cfg',$GLOBALS["_CFG"]);
		//Mylib::shopconfig();//加载商城配置信息;以G('shopconf')方式访问;//如 
		/* 非utf8转码 */
		if (C('CHARSET') != 'utf-8' && isset($_REQUEST['ajax'])){
			$_FILES = md_iconv_deep('utf-8', CHARSET, $_FILES);
			$_GET = md_iconv_deep('utf-8', CHARSET, $_GET);
			$_POST = md_iconv_deep('utf-8', CHARSET, $_POST);
		}
		LL("common");		
		$GLOBALS['_LANG']=L();//载入语言;
 	    $this->db(); 
		$this->shop_init();	 
		
    }
		//压缩函数
	function ob_gzip($content){   
		if(!headers_sent()&&extension_loaded("zlib")&&strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")){
			$content = gzencode($content,9);       
			header("Content-Encoding: gzip");
			header("Vary: Accept-Encoding");
			header("Content-Length: ".strlen($content));
		}
		return $content;
	}
	public function test(){

		$a=array('account_log','admin_log','goods','goods_attr','goods_cat','goods_spec_attr','group_goods','link_goods','order_goods','order_info','uploadedfile');
		foreach($a as $k){
		echo "TRUNCATE TABLE `jp_".$k."` ;<br>";
		
		}

		 
		//dump($_SESSION);
	
	}
     /*调用购物车信息; 
	 */
	public function insert_cart_info()
	{
		$sql = 'SELECT SUM(goods_number) AS number, SUM(goods_price * goods_number) AS amount' .
			   ' FROM ' . gettable('cart') .
			   " WHERE session_id = '" . G('SESS_ID') . "' AND rec_type = '" . CART_GENERAL_GOODS . "'";
		$row = G('db')->GetRow($sql);

		if ($row)
		{
			$number = intval($row['number']);
			$amount = floatval($row['amount']);
		}
		else
		{
			$number = 0;
			$amount = 0;
		}

		$str = sprintf($GLOBALS['_LANG']['cart_info'], $number, price_format($amount, false));
        $bag=array('num'=>$number,'title'=>$str);
		return $bag;//'<a href="'.U('Order/cart').'" title="查看购物袋">' . $str . '</a>';
	}
	public function shop_init(){
		
		$this->cookie_domain = isset($cfg['cookie_domain']) ? $cfg['cookie_domain'] : '';
        $this->cookie_path = isset($cfg['cookie_path']) ? $cfg['cookie_path'] : '/';
		if ($GLOBALS["_CFG"]['shop_closed'] == 1){
			/* 商店关闭了，输出关闭的消息 */
			header('Content-type: text/html; charset='.CHARSET);
			die('<div style="margin: 150px; text-align: center; font-size: 14px"><p>' . L('shop_closed') . '</p><p>' . $GLOBALS["_CFG"]['close_comment'] . '</p></div>');
		}
		
		 /*
		if (is_spider())
		{
			# 如果是蜘蛛的访问，那么默认为访客方式，并且不记录到日志中 		
			$_SESSION = array();
			$_SESSION['user_id']     = 0;
			$_SESSION['user_name']   = '';
			$_SESSION['email']       = '';
			$_SESSION['user_rank']   = 0;
			$_SESSION['discount']    = 1.00;
		}
		*/
			
		if (!defined('INIT_NO_USERS')){
				/* 会员信息 */
				LC('@.Lib.Integrate');
				$conf = unserialize($GLOBALS["_CFG"]['integrate_config']);				
				$user =new mdlshop($conf);
				$GLOBALS['user']=$user;					
				G('user',$GLOBALS['user']);
				$this->_init_session();	 
				// ECHO G('SESS_ID');

				//	DUMP($_COOKIE['MDL_ID']);
				// dump($_COOKIE);
				if (empty($_SESSION['user_id'])){	
					
					
					if ($user->get_cookie()){						
					 
						if ($_SESSION['user_id'] > 0){
							update_user_info();
						}
					}else{					 
						$_SESSION['user_id']     = 0;
						$_SESSION['user_name']   = '';
						$_SESSION['email']       = '';
						$_SESSION['user_rank']   = 0;
						$_SESSION['discount']    = 1.00;
						 
						if (!isset($_SESSION['login_fail'])){
							$_SESSION['login_fail'] = 0;
						}
					}
				}				
				$v=G('V');
				if (isset($v))
				{
					G('V')->assign('mdl_session', $_SESSION);
				}
				
			}
	
	
	}
	public  function _init_session(){
		//header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA div COM NAV OTC NOI DSP COR"');  
		@ini_set('memory_limit',          '64M');
		@ini_set('session.cache_expire',  180);
		@ini_set('session.use_trans_sid', 0);
		@ini_set('session.use_cookies',   1);
		@ini_set('session.auto_start',    0);
		@ini_set('display_errors',        1);
 		if(C('SESSION_TYPE')==1){			 
			LC('@.Lib.Session');
			$GLOBALS['sess']=$sess = new Session(G('db'), gettable('sessions'), gettable('sessions_data'), 'MDL_ID');
			G('session', $sess);			 
			G('SESS_ID',$sess->session_id);           
		}elseif(C('SESSION_TYPE')==0){		 
			session_start();
		}else{
		    E(L('session.no'));
		}
    }
	 
	public function display($f=''){		
		 
		$this->pageinfo();	
		$userinfo=$_SESSION['userinfo'];
		$username=$userinfo['user_name'];
		
		$this->assign("username",$username);
		$this->assign("userinfo",$userinfo);
		$this->assign('footer',$this->getfooter());
		$this->assign("shopbaginfo",$this->insert_cart_info() );
		 

		parent::display($f);
	}
	public function getfooter(){
		 $cat=F("cat_foot");		   
		 if(empty($cat)){		
		   $arr=array('newuser','order','serveice','callcenter');
		   $where=db_create_in($arr,'cat_ename');		   
	       $sql="select cat_id,cat_name,cat_ename from ".gettable('article_cat')." where ".$where." order by  sort_order asc";
		   $rs=G('db')->getAll($sql);
		   $ids=array();
		   $cat=array();
		   foreach($rs as $k=>$v){
		           $ids[]=$v['cat_id'];
				   $cat[$v['cat_id']]=$v;
		   }

		   $where=db_create_in($ids,'cat_id');
		   $sql="select article_id,title ,cat_id from ".gettable('article')." where ".$where." order by  article_id asc";
		   $rs=G('db')->getAll($sql);
		   foreach($rs as $k=>$v){
			   $v['title']=left($v['title'],10,1);
		       $cat[$v['cat_id']]['news'][]=$v;
		   }
		   F("cat_foot",$cat,-1);
		 }
		 return $cat;

		  // dump($cat);
		    
	
	
	
	}
	//页面信息,供js调用;
	function pageinfo(){
			$SELF=$_SERVER['REQUEST_URI'];
		    $data=APPDATA;//.str_replace("./",'/',DATA_PATH);
		    $menuid=getgp("menuid");
			$arr=$_REQUEST;	
			      
			define('__ACTION__',__URL__.'/'.G('CACT'));	
		 
		    G('APPURL',PHP_FILE);
			$query=getquery();//查询条件;
			@extract($arr);	 
			$ff=str_replace('/index.php','',PHP_FILE);
			define('__URL__',$ff.'/'.G('CAPP'));  
			$s.= "function PageInfo(){";
			$s.=  "		var o={};";		 
			$s.=  "		o.ROOT='".__ROOT__."';";
			$s.=  "		o.APP='".$ff."';";
			$s.=  "		o.APP2='".PHP_FILE."';";
			$s.=  "		o.URL='".__URL__."';";
			$s.=  "		o.ACTION='".G('CACT')."';";
			$s.=  "		o.VAR_APP='".C('VAR_APP')."';";
			$s.=  "		o.VAR_ACT='".C('VAR_ACT')."';";
			$s.=  "		o.SELF='".$SELF."';";	
			$s.=  "     o.query='$query';";
			$s.=  "		o.name='".APPNAME."';";			 
			$s.=  "		o.data='".$data."';";
			$s.=  "		o.menuid='".$menuid."';";
			$s.="       o.public='".APPPUBLIC."'; ";
			foreach($arr as $key=>$v){
			   if(!empty($v)){
				    $v=($v);
					//$s.="o.$key='$v';"; 
			   }
			}
			$s.=  "     return o;"; 
			$s.= "};";	
			$s.= "var PagePI=new PageInfo();";	
			$this->assign("pageinfo",$s);
			return $s;
	}
//得到一条记录
	public function getone(){
		LC("@.Lib.Json");
		$id=intval(GetGP("id"));		
		$App=D($this->name);
		$list=$App->find($id);
		$data=new Json();
		echo $data->encode($list);
		//return $list;
	}
	/****************以下函数为特殊处理 输助函数*/
    /*ajax 数据接口 */
   public function Ajaxdata(){
	  //模型名称;查询条件;类型识别;	   
	   LC("@.Lib.Ajaxdata");
	   $data = file_get_contents("php://input");  
		 // dump($data);
		if(empty($data)){
			$data=$_POST;
		}  	     
	    //$b=$json->decode($data);
	    $dt= md_json_decode($data);
	   // dump($dt) ;
	   //echo $data;
	    $data=new Ajaxdata($dt);
	   //$data->init();
   }
   public function getby($key){
		 $a=$this->params;
		 $len=count($a);		 
		 if(!is_array($a)||count($a)%2!=0){
			return null;
		 }
		 $params=array();
		 for ($i = 0; $i <= count($a); ) {
			$tem=$a[$i];
			$i++;
			if($a[$i]!=null&&$a[$i]!='null'){
			$parmas[$tem]=$a[$i];
			}
			$i++;
		}
		return isset($parmas[$key])?$parmas[$key]:null;
   
   }
   public function getbyarams(){
		 $a=$this->params;
		 $len=count($a);		 
		 if(!is_array($a)||count($a)%2!=0){
			return null;
		 }
		 $params=array();
		 for ($i = 0; $i <= count($a); ) {
			$tem=$a[$i];
			$i++;
			if($a[$i]!=null&&$a[$i]!='null'){
				 
				$parmas[$tem]=$a[$i];
			}
			$i++;
		}
		// dump($parmas);
		$sign=$parmas['sign'];
	    unset($parmas['sign']);	
		$string = implode(",",$parmas);
 //dump(md5($string));
// dump(md5($sign));
		if(!empty($sign)&&$sign!=md5($string)){
			return false;
		}else{
		    return true;
		};
		 
   
   }  
   /*生成分页
	   $num 总记录数;
	   $perpage 每页记录数 ;
	   $curpage 当前页;
	   $mpurl url 地址；
   */
	function page($num, $perpage, $curpage, $mpurl) {		 
		$multipage = '';
		//$mpurl .= strpos($mpurl, '?') ? '&' : '?';
		if($num > $perpage) {
			$page = 10;
			$offset = 2;

			$pages = @ceil($num / $perpage);

			if($page > $pages) {
				$from = 1;
				$to = $pages;
			} else {
				$from = $curpage - $offset;
				$to = $from + $page - 1;
				if($from < 1) {
					$to = $curpage + 1 - $from;
					$from = 1;
					if($to - $from < $page) {
						$to = $page;
					}
				} elseif($to > $pages) {
					$from = $pages - $page + 1;
					$to = $pages;
				}
			}

			$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.pageurl($mpurl,1).'" class="first"'.$ajaxtarget.'>...</a>' : '').
			($curpage > 1 && !$simple ? '<a href="'.pageurl($mpurl,($curpage - 1)).'" class="prev"'.$ajaxtarget.'>上一页</a>' : '');
			for($i = $from; $i <= $to; $i++) {
				$multipage .= $i == $curpage ? '<strong  >'.$i.'</strong>' :
				'<a href="'.pageurl($mpurl,$i).'">'.$i.'</a>';
			}

			$multipage .= ($curpage < $pages && !$simple ? '<a href="'.pageurl($mpurl,($curpage + 1)).'" class="next"'.$ajaxtarget.'>下一页</a>' : '').
			($to < $pages ? '<a href="'.pageurl($mpurl,$pages).'" class="last"'.$ajaxtarget.'>... '.$realpages.'</a>' : '').
			(!$simple && $pages > $page && !$ajaxtarget ? '' : '');
           /*
			$multipage .= ($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="next"'.$ajaxtarget.'>&rsaquo;&rsaquo;</a>' : '').
			($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="last"'.$ajaxtarget.'>... '.$realpages.'</a>' : '').
			(!$simple && $pages > $page && !$ajaxtarget ? '<kbd ><input type="text" name="custompage" size="3" onkeydown="if(event.keyCode==13) {window.location=\''.$mpurl.'page=\'+this.value; return false;}" /></kbd>' : '');
          */
			$multipage = $multipage ? '<div class="pages">'.(!$simple ? '<em>&nbsp;'.$num.'&nbsp;</em><em>&nbsp;'.$curpage.'/'.$pages.'&nbsp;</em>' : '').$multipage.'</div>' : '';
		}
		return $multipage;
	}
    /*
	返回，起始，和终止的记录数;
	*/
	function page_get_start($page, $ppp, $totalnum) {
		$totalpage = ceil($totalnum / $ppp);
		$page =  max(1, min($totalpage, intval($page)));
		return ($page - 1) * $ppp;
	} 

	//获取本栏目对应的后台分类id;
	public function cate_id($id=1){	
		$dt=array('Newgoods','Woman','Man','Match','Newgoods');
        $where=$id==0?"1":'show_in_nav='.$id.'';
		$data=$this->db->fetch_first('select cat_id from '.gettable('category').' where '.$where.''); 		   
		//echo 'select cat_id from '.gettable('category').' where '.$where.'';
		 
		$this->cid=$id==0?0:$data['cat_id'];		
		$this->catname=$dt[$id];
		//echo $this->catname;
	}

	//获取查询参数
	public function getfilter(){
	   $f=array();   
	  
	   if( !is_null($this->getby('cat')) ){
	     $f['cat']=$this->getby('cat');
	   }else{
	     $f['cat']=$this->cid;
	   }
	  // dump($f);
	   if( !is_null( $this->getby('brand') ) ){
	     $f['brand']=$this->getby('brand');
	   }
	   if( !is_null($this->getby('color')) ){
	     $f['color']=$this->getby('color');
	   }
	   if( !is_null($this->getby('size')) ){
	     $f['size']=$this->getby('size');
	   }
	   if( !is_null($this->getby('price')) ){
	     $f['price']=$this->getby('price');
	   }
	  
	   $cl=my_url_format_arr($this->getby('cl'));   
 	   $cc=array();
       //页面
	   if( !empty($cl['page'])  ){
	     $cc['page']=$cl['page'];
	   }else{
	     $cc['page']=1;
	   }
	   if( !is_null($cl['psize']) ){
	     $cc['psize']=$cl['psize'];
	   }else{
		 $p=get_p_size();
	     $cc['psize']=$p[0];
	   }
	   if(!empty($cl['oby']) ){
	     $cc['oby']=$cl['oby'];
	   }else{
	     $cc['oby']='1';	   
	   }

	   if( !is_null($cl['sec']) ){
	     $cc['sec']=$cl['sec'];
	   }else{
	     $cc['sec']='1';	   
	   }
	   if( !is_null($cl['tt']) ){
	     $cc['tt']=$cl['tt'];
	   }else{
	     $cc['tt']=G('CAPP');	   
	   }

	   if( !is_null($cl['day']) ){
	     $cc['day']=$cl['day'];
	   }else{
		 $cc['day']=-1;
	   } 
	   
	   if( !is_null( getgp('keyword') )|| !is_null( $cl['keyword'] )){
	     $cc['keyword']=is_null(getgp('keyword'))?$cl['keyword']:getgp('keyword');
	   }else{	   
		 $cc['keyword']=-1;
	   }
	   //dump($cc);
	   $f['cl']=my_url_format($cc);
	  // dump(G());
	 // dump($f);
	   $_SESSION["goods_filter"] =   urlencode(serialize($f));	   
       return $f;

	} 
	 
	 
	//排序,及分页大小
   function get_orderby_psize($act){  
		 $f=my_url_format_arr($this->getby('cl'));	 
		 $n_by=array(
				 array('name'=>'1','desc'=>'价格'),
				 array('name'=>'2','desc'=>'最新'),
				 array('name'=>'3','desc'=>'人气'),
		 );	 
		 $str=array();
		 foreach($n_by as $key=>$v){
			// echo goods_url(array('oby'=>$v['name']))."<br>";
		   if($v['name']==$f['oby']){
			  $asc=$f['sec']=='1'?"↑":'↓';
			  $sec=$f['sec']=='1'?"2":'1';
			  $str[]="<a href='".goods_url(array('oby'=>$v['name'],'sec'=>$sec),true,$act)."' class='Line_a'><strong>".$v['desc']."&nbsp;".$asc."</strong></a>";
		   }else{
			  $str[]="<a href='".goods_url(array('oby'=>$v['name'],'sec'=>$sec),true,$act)."' class='Line_a'>".$v['desc']."</a>";
		   }
		 }
		 $this->assign('set_orderby',implode("&nbsp;|&nbsp;",$str) );
		 $psize=get_p_size();
		 $str='';	
		 foreach($psize as $key){
			if($key==$f['psize']){
				$str.='<a href="'.goods_url(array('psize'=>$key),true,$act).'" class="Categories_Menu_a"><strong>'.$key.'</strong></a>&nbsp;&nbsp;&nbsp;&nbsp;';
			}else{
				$str.='<a href="'.goods_url(array('psize'=>$key),true,$act).'" class="Categories_Menu_a">'.$key.'</a>&nbsp;&nbsp;&nbsp;&nbsp;';
			
			}
		 }   
		$this->assign('set_psize',$str );
   }
    
//获取游览历史
	function get_history(){
		$str = '';
		if (!empty($_COOKIE['MDL']['history'])){
			$where = db_create_in($_COOKIE['MDL']['history'], 'g.id');
          
			$sql="select g.id,g.picture,a.goods_name,a.shop_price".
				" from ".gettable('goods_spec_attr')." as g " .
				"LEFT JOIN " . gettable('goods') . " AS a ON g.goods_id=a.id ".				 
				" where $where AND a.is_on_sale = 1 AND a.is_alone_sale = 1 AND a.is_delete = 0";
			
			$query = G('db')->query($sql);
			//$res = array();
			while ($row = G('db')->fetch_array($query)){
				$goods['goods_id'] = $row['id'];				 
				$goods['goods_name'] = $row['goods_name'];
				//$goods['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
				$goods['goods_thumb'] = get_image_path($row['id'], $row['picture'], true);
				$goods['shop_price'] = price_format($row['shop_price']);
				$goods['url'] = goods_nav_url( array('gid'=>$row['id']),true);
				$str.='<div class=history_box ><a href="'.$goods['url'].'" target="_blank"><img src="'.$goods['goods_thumb'].'" alt="'.$goods['goods_name'].'" class="B_blue" width=64 /></a></div>';					
			}
		 
		}
		// dump($GLOBALS['_LANG']);
		return $str;
	}
	//搜不到产品的时候，显示热销和推荐;
	function getsearchno(){

			$sql="select gid, goods_id,goods_name,picture,shop_price,is_best,is_hot,market_price,brand_id from view_goods_all ".
				"where 1 and is_delete=0 and is_on_sale=1 AND is_alone_sale = 1 and default_on=1" ;			 
			$rs = G('db')->getAll($sql);
			$hot_list=array();//热销产品;
			$best_list=array();//精品推荐产品;
			$list=G('db')->fetch_array($query);
			//dump($rs);
			$brand_all=get_brand_list();
			foreach($rs as $key=>$row){	
				$goods['goods_id'] = $row['gid'];				 
				$goods['goods_name'] = $row['goods_name'];
				//$goods['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
				$goods['goods_thumb'] = get_image_path($row['id'], $row['picture'], true);
				$goods['shop_price'] = price_format($row['shop_price']);
				$goods['market_price'] = price_format($row['market_price']);
				$goods['url'] = goods_nav_url( array('gid'=>$row['gid']),true);
				$goods['brand_name'] = $brand_all[$row['brand_id']];
				
                if($row['is_best']&&count($best_list)<4){
					$best_list[]=$goods;				
				}
				if($row['is_hot']&&count($hot_list)<4){
					$hot_list[]=$goods;
				
				}
			}
			return array('best'=>$best_list,'hot'=>$hot_list); 
	
	}

	function show_message($content, $links = '', $hrefs = '', $type = 'info', $auto_redirect = true){
		$msg['content'] = $content;
		if (is_array($links) && is_array($hrefs)){
			if (!empty($links) && count($links) == count($hrefs)){
				foreach($links as $key =>$val){
					$msg['url_info'][$val] = $hrefs[$key];
				}
				$msg['back_url'] = $hrefs['0'];
			}
		}else{
			$link   = empty($links) ? $GLOBALS['_LANG']['back_up_page'] : $links;
			$href    = empty($hrefs) ? 'javascript:history.back()'       : $hrefs;
			$msg['url_info'][$link] = $href;
			$msg['back_url'] = $href;
		}

		$msg['type']    = $type;
		//dump($_SESSION);
	   // $position = assign_ur_here(0, $GLOBALS['_LANG']['sys_msg']);
		$this->assign('page_title', $position['title']);   // 页面标题
		$this->assign('ur_here',    $position['ur_here']); // 当前位置    
		$this->assign('auto_redirect', $auto_redirect);
		$this->assign('message', $msg);
		$file=$type=="info"?'message':'errorinfo';
		$this->display($file);
		exit;
	}
	function setcookie($key, $value, $life = 0, $httponly = false) {
		(!defined('MDL_COOKIEPATH')) && define('MDL_COOKIEPATH', '/');
		(!defined('MDL_COOKIEDOMAIN')) && define('MDL_COOKIEDOMAIN', '');

		if($value == '' || $life < 0) {
			$value = '';
			$life = -1;
		}
	 
		$life = $life > 0 ? $this->time + $life : ($life < 0 ? $this->time - 31536000 : 0);
		$path = $httponly && PHP_VERSION < '5.2.0' ? MDL_COOKIEPATH."; HttpOnly" : MDL_COOKIEPATH;
		$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
		if(PHP_VERSION < '5.2.0') {
			setcookie($key, $value, $life, $path, MDL_COOKIEDOMAIN, $secure);
		} else {
			setcookie($key, $value, $life, $path, MDL_COOKIEDOMAIN, $secure, $httponly);
		}
	}
	//发推荐信;
  public function sendemail($uid, $user_name, $email, $code){
     
		/* 设置重置邮件模板所需要的内容信息 */
		$template    = get_mail_template('tuijian_template');
 		$user_name=$_SESSION['user_name'];
		// dump($_POST);
		$email=getgp('mdl_mail');
		$is_ajax=getgp('is_ajax');
		$a['send_date']=date('Y-m-d');
		$a['user_name']=$user_name;
		$this->assign($a);
		// echo $email;

		$content=$this->view->eval_php($template['template_content']);
		 
		 
		/* 发送确认重置密码的确认邮件 */
		if (send_mail($user_name, $email,  md_iconv('utf-8','gb2312',$template['template_subject']), $content, $template['is_html'])){
			if($is_ajax==1){
				echo 1;
			}else{
				$this->show_message('邮件已发送');
			}
		}else{
			if($is_ajax==1){
				echo 0;
			}else{
				$this->show_message('邮件发送失败');
			}
			
		}
	}
   //取得产品;
	function getAllGoods($cat_id,$filter=array() ){
	  
		
		$cat_list=array();#分类列表;
		$color_list=array();#颜色列表;
		$size_list=array();#尺寸列表；
		$price_list=array();#价格列表；
		$goods_ids=array();
		$children = get_children($cat_id);
	     //dump($children);
        //品牌;
		$brand = isset($filter['brand']) && intval($filter['brand']) > 0 ? intval($filter['brand']) : 0;
		if($filter['price']){
				$a=getprice($filter['price']);
				 
				$price_min = isset($a[0]) && intval($a[0]) > 0 ? intval($a[0]) : 0;
				$price_max = isset($a[1]) && intval($a[1]) > 0 ? intval($a[1]) : 0; 
		}else{
			$price_min=0;
			$price_max=0;
		} 
		$color = isset($filter['color']) && intval($filter['color']) > 0 ? intval($filter['color']) : 0;
		$size = isset($filter['size']) && intval($filter['size']) > 0 ? intval($filter['size']) : 0;

		 
       
	    $list=array();
		$where = "g.is_on_sale = 1 AND g.is_alone_sale = 1 AND ".
				"g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ')';

		if ($brand > 0)
		{
			$where .=  "AND g.brand_id=$brand ";
		}

		if ($price_min > 0)
		{
			$where .= " AND g.shop_price >= $price_min ";
		}

		if ($price_max > 0)
		{
			$where .= " AND g.shop_price <= $price_max ";
		}
		if ($color > 0)
		{
			$where .= " AND g.color = $color ";
		}
		if ($size > 0)
		{
			$where .= " AND g.size= $size ";
		}
		  
		$cl= $cl=my_url_format_arr($filter['cl']); 
 
		if($cl['day']>=0&&!empty($cl['day'])){
			 
				$a=$cl['day'];
				$b=betweenday($a);
				// echo date("Y-m-d",$b[0])."<br>";
				//  echo date("Y-m-d",$b[1]);
				// echo  local_strtotime($a);
				$where.=" and '".$b[0]."'<add_time ";		
				$where.=" and add_time<='".$b[1]. "' ";	 
		} 
  
		$keyword=$cl['keyword'];
		if($cl['keyword']&&$cl['keyword']!=-1){
			//g.brand_name like '%".$keyword."%' or g.cat_name like '%".$keyword."%' or
			$where.=" and ( g.goods_name like '%".$keyword."%' or g.goods_desc like '%".$keyword."%' )";	
		}
		 
		// dump( $where);
		/* 获得商品列表 */
		$sql = 'SELECT g.gid,g.goods_id,cat_id, g.goods_name, g.brand_id, g.market_price, g.is_new, g.is_best, g.is_hot,g.is_promote,g.quantity,g.locknum, g.shop_price AS org_price, ' .
					"IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, g.goods_type, " .
					'g.promote_start_date, g.promote_end_date, g.goods_brief, g.picture,g.color,g.size ,g.default_on ' .
				'FROM view_goods_all AS g ' .
				'LEFT JOIN ' . gettable('member_price') . ' AS mp ' .
					"ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' " ;
				"WHERE $where  ";
	    $sql_=$sql." where $where ";
		//echo $sql_;
		$rs=G('db')->getAll($sql_);
		//dump($rs);
		 //全部品牌数据
		$brand_all=getBrandList();		
		$color_size=getcolor_size();	
		
		foreach($rs as $k=>$v){	
			 
			if(!empty($v['brand_id'])){			
			 $brandlist[$v['brand_id']]=$brand_all[$v['brand_id']];
			}
			if(!empty($v['cat_id'])){
				 $cat_list[$v['cat_id']]= $v['cat_id'];//$v['cat_name'] ;
			}			 
			$color_list[$v['color']]= $color_size[$v['color']]['spec_logo'] ;
			$sizelist[$v['size']]= $color_size[$v['size']] ;
			$price_list=getshowprice($v['shop_price']);
		 } 
 		 $brandlist=multi_sort($brandlist,'brand_name');
		 $brand_list=array();
		 foreach($brandlist as $key=>$val){		 
			$brand_list[$val['brand_id']]=$val;
		 }

		 $sizelist=multi_sort($sizelist,'sort_order');
		 foreach($sizelist as $key=>$val){		 
			$size_list[$val['spec_id']]=$val['spec_name'];
		 }
    // dump($size_list);
		 //如果没有选择尺寸和颜色，则以默认规格为准
		if(!isok($filter['color'])&&!isok($filter['size'])){
			$where.=" and g.default_on=1 ";	
		}	
	 	$where.=" group by g.goods_id";
		$oby=orderby_cat();
		$cl=my_url_format_arr($this->getby('cl')); 
		if($cl['oby']){
				$sec=$cl['sec']=="1"?'asc':'desc';
				$where.=' order by g.'.$oby[$cl['oby']].' '.$sec.' ';			 
		} 		
	 
		$where =$where ? " WHERE  $where" : '';
		$sql_=$sql.$where;	 
		$goods_rs=G('db')->fetch_all($sql);	
		
		$data1 = $this->db->fetch_all($sql."   $where");		 
		$num=count($data1);
		//dump($num);
	 
		$cl=my_url_format_arr($this->getby('cl')); 
		$page=$cl['page'];
		$psize=$cl['psize'];
		//dump($cl);
		#$page=$this->getby('page')?intval($this->getby('page')):1;
		#$psize=$this->getby('psize')?$this->getby('psize'):20;
		 
	 
		$start = $this->page_get_start($page, $psize, $num);
		//echo $;
        if($psize!=0){
			//echo "SELECT * FROM view_goods_all as g  $where LIMIT $start, $psize";
			 // echo $sql."  $where LIMIT $start, $psize";
			$goods_rs = $this->db->fetch_all($sql."  $where LIMIT $start, $psize");				 
			///$CP=$this->getby('page')?intval($this->getby('page')):1;			 
		    $url=goods_url(array('page'=>'{page}'),true);
		    $multipage = $this->page($num, $psize, $page,  $url);
		}else{		
			$goods_rs = $this->db->fetch_all($sql."  $where ");	
		}
		//dump($multipage);
		 
		 $list['brand_list'] =$brand_list;
		// dump($cat_list);
		 $list['cat_index']=get_catlist($cat_id,$cat_list);
		 $list['cat_list']=format_catlist($cat_id,$cat_list);
		
		$goods_list=array();
		foreach($goods_rs as $k=>$v){
              
				$v['brand_name']=$brand_list[$v['brand_id']]['brand_name'];
				//热销;
				$v['icon']='0';
				if($v['is_hot']==1){
				    $v['icon']=1;
				}
				//促销
				if($v['is_promote']==1){
				    $v['icon']=4;
				}
				//库存数量为1
				if(($v['quantity']-$v['locknum'])==1){
				    $v['icon']=5;
				}	
				$v['picturet']=$v['picture'];
				$v['picture']=str_replace('Thumb','Small',$v['picture']);
				$goods_list[]=$v;
		}
		 
		 //dump($goods_list);
		$list['goods_list']=$goods_list;
		  asort($price_list); 		 
		 $list['price_list']= $price_list; 	 
		 $list['color_list']=$color_list;
		 //dump($size_list);
		 $list['size_list']=$size_list;
		 $list['multipage']=$multipage;
		 return $list;
   
	 }
	function init_var() {
		$this->time = time();
		$cip = getenv('HTTP_CLIENT_IP');
		$xip = getenv('HTTP_X_FORWARDED_FOR');
		$rip = getenv('REMOTE_ADDR');
		$srip = $_SERVER['REMOTE_ADDR'];
		if($cip && strcasecmp($cip, 'unknown')) {
			$this->onlineip = $cip;
		} elseif($xip && strcasecmp($xip, 'unknown')) {
			$this->onlineip = $xip;
		} elseif($rip && strcasecmp($rip, 'unknown')) {
			$this->onlineip = $rip;
		} elseif($srip && strcasecmp($srip, 'unknown')) {
			$this->onlineip = $srip;
		}
		preg_match("/[\d\.]{7,15}/", $this->onlineip, $match);
		$this->onlineip = $match[0] ? $match[0] : 'unknown';

		define('FORMHASH', $this->formhash());
		$_GET['page'] =  max(1, intval(getgpc('page')));

		//include_once UC_ROOT.'./view/default/main.lang.php';
		//$this->lang = &$lang;
	}

   function check_priv() {
		$username = $this->sid_decode($this->view->sid);
		if(empty($username)) {
			header('Location: '.UC_API.'/admin.php?m=user&a=login&iframe='.getgpc('iframe', 'G').($this->cookie_status ? '' : '&sid='.$this->view->sid));
			exit;
		} else {
			$this->user['isfounder'] = $username == 'UCenterAdministrator' ? 1 : 0;
			if(!$this->user['isfounder']) {
				$admin = $this->db->fetch_first("SELECT a.*, m.* FROM ".UC_DBTABLEPRE."admins a LEFT JOIN ".UC_DBTABLEPRE."members m USING(uid) WHERE a.username='$username'");
				if(empty($admin)) {
					header('Location: '.UC_API.'/admin.php?m=user&a=login&iframe='.getgpc('iframe', 'G').($this->cookie_status ? '' : '&sid='.$this->view->sid));
					exit;
				} else {
					$this->user = $admin;
					$this->user['username'] = $username;
					$this->user['admin'] = 1;
					$this->view->sid = $this->sid_encode($username);
					$this->setcookie('sid', $this->view->sid, 86400);
				}
			} else {
				$this->user['username'] = 'UCenterAdministrator';
				$this->user['admin'] = 1;
			}
			$this->view->assign('user', $this->user);
		}
	}
	function _call($a, $arg) {
		if(method_exists($this, $a) && $a{0} != '_') {
			$this->$a();
		} else {
			exit('Method does not exists');
		}
	}
   function sid_encode($username) {
		$ip = $this->onlineip;
		$agent = $_SERVER['HTTP_USER_AGENT'];
		$authkey = md5($ip.$agent.UC_KEY);
		$check = substr(md5($ip.$agent), 0, 8);
		return rawurlencode($this->authcode("$username\t$check", 'ENCODE', $authkey, 1800));
	}

	function sid_decode($sid) {
		$ip = $this->onlineip;
		$agent = $_SERVER['HTTP_USER_AGENT'];
		$authkey = md5($ip.$agent.UC_KEY);
		$s = $this->authcode(rawurldecode($sid), 'DECODE', $authkey, 1800);
		if(empty($s)) {
			return FALSE;
		}
		@list($username, $check) = explode("\t", $s);
		if($check == substr(md5($ip.$agent), 0, 8)) {
			return $username;
		} else {
			return FALSE;
		}
	}
	function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

		$ckey_length = 4;	// 随机密钥长度 取值 0-32;
		// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
		// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
		// 当此值为 0 时，则不产生随机密钥

		$key = md5($key ? $key : UC_KEY);
		$keya = md5(substr($key, 0, 16));
		$keyb = md5(substr($key, 16, 16));
		$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

		$cryptkey = $keya.md5($keya.$keyc);
		$key_length = strlen($cryptkey);

		$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
		$string_length = strlen($string);

		$result = '';
		$box = range(0, 255);

		$rndkey = array();
		for($i = 0; $i <= 255; $i++) {
			$rndkey[$i] = ord($cryptkey[$i % $key_length]);
		}

		for($j = $i = 0; $i < 256; $i++) {
			$j = ($j + $box[$i] + $rndkey[$i]) % 256;
			$tmp = $box[$i];
			$box[$i] = $box[$j];
			$box[$j] = $tmp;
		}

		for($a = $j = $i = 0; $i < $string_length; $i++) {
			$a = ($a + 1) % 256;
			$j = ($j + $box[$a]) % 256;
			$tmp = $box[$a];
			$box[$a] = $box[$j];
			$box[$j] = $tmp;
			$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
		}

		if($operation == 'DECODE') {
			if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
				return substr($result, 26);
			} else {
				return '';
			}
		} else {
			return $keyc.str_replace('=', '', base64_encode($result));
		}

	}

	

}
?>